<template>
  <div>
    <vxe-toolbar>
      <template #buttons>
        <el-button type="success" icon="el-icon-plus" size="medium" @click="insertEvent">新增记录</el-button>
        <!-- <el-button type="success" icon="el-icon-printer" size="medium" @click="printEvent">打印</el-button> -->
        <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索" @input="searchEvent"></vxe-input>
      </template>
    </vxe-toolbar>
    <vxe-table resizable ref="XTable" show-overflow border max-height="800" stripe highlight-hover-row highlight-current-row :loading="loading" :data="dataList" @sort-change="sortChange">
      <vxe-table-column field="name" title="姓名" sortable></vxe-table-column>
      <vxe-table-column field="appellation" title="称谓" sortable></vxe-table-column>
      <vxe-table-column field="workUnit" title="工作单位" sortable></vxe-table-column>
      <vxe-table-column field="post" title="职位职务" sortable></vxe-table-column>
      <vxe-table-column field="phone" title="联系电话" sortable></vxe-table-column>
      <vxe-table-column field="" title="操作" width="110">
        <template #default="{ row,rowIndex }">
          <el-button @click="editEvent(row,rowIndex)" type="success" size="medium" icon="el-icon-edit" circle></el-button>
          <el-button @click="deleteEvent(row)" type="danger" size="medium"  icon="el-icon-delete" circle></el-button>
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize"
      :total="page.totalResult" :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
      @page-change="handlePageChange">
    </vxe-pager>
    <vxe-modal v-model="insertModal" title="家庭成员">
      <template #default>
         <el-form inline-message ref="insertForm" :rules="rules" :model="insertForm" label-width="110px">
           <el-form-item label="姓名" prop="name">
             <el-input v-model="insertForm.name"></el-input>
           </el-form-item>
           <el-form-item label="称谓">
             <el-select v-model="insertForm.appellationId" filterable clearable style="width: 100%;" placeholder="请选择">
               <el-option :label="item" :value="key" v-for="(item,key,index) in dict_appellation" :key="index"></el-option>
             </el-select>
           </el-form-item>
           <el-form-item label="工作单位">
             <el-input v-model="insertForm.workUnit"></el-input>
           </el-form-item>
           <el-form-item label="职位职务">
             <el-input v-model="insertForm.post"></el-input>
           </el-form-item>
           <el-form-item label="电话">
             <el-input v-model="insertForm.phone"></el-input>
           </el-form-item>
           <el-form-item>
               <el-button type="warning" size="small" @click="insertModal = false">取消</el-button>
               <el-button type="success" size="small" icon="el-icon-s-promotion" @click="insertSave">保存</el-button>
           </el-form-item>
         </el-form>
      </template>
    </vxe-modal>
  </div>
</template>

<script>
  import {person_family,person_family_insert,person_family_update,person_family_delete} from '@/api/person.js'
  import {getAppellation} from '@/api/dict.js'
  export default{
    props:['pId'],
    data() {
      return {
        defaultDataList: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        dict_appellation: {},
        filterName: '',
        insertModal: false,
        insertForm: {
          name: '',
          appellationId: '',
          workUnit: '',
          phone: '',
          post: '',
        },
        sportItemData: [],
        rules: {
          name: [
            { required: true, message: '这是必填项', trigger: 'blur' },
          ],
        },
        isInsert: true,
        flowId: '',
        search: false,
        currentIndex: null,
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.person_family()
      })
    },
    computed: {
      openDateValid() {
        if(this.insertForm.openDate && this.insertForm.closeDate){
          if(this.insertForm.openDate > this.insertForm.closeDate) {
            this.$message.error('开始时间必须小于结束时间！')
            return false
          }else{
            return true
          }
        }else{
          return true
        }
      }
    },
    watch: {
      filterName(val) {
    	if(!val){
    	  this.page = {
    	  currentPage: 1,
    	  pageSize: 10,
    	  totalResult: 0,
    	  }
    	  this.search = false
    	  this.findList()
    	}
      }
    },
    methods: {
      deleteEvent(row) {
        this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          person_family_delete({flowId:row.flowId}).then(res=>{
            if(res.code === 200 ) {
              this.defaultDataList.forEach((item,index)=>{
              	if(item.flowId == row.flowId){
              	  this.defaultDataList.splice(index,1)
              	}
              })
              this.init_data(this.defaultDataList)
              this.findList()
              this.$message.success('删除成功！')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      editEvent(row,rowIndex) {
        this.currentIndex = rowIndex
        this.flowId = row.flowId
        this.insertForm.name = row.name
        this.insertForm.appellationId = row.appellationId+''
        this.insertForm.workUnit = row.workUnit
        this.insertForm.phone = row.phone
        this.insertForm.post = row.post
        this.isInsert = false
        this.insertModal = true
      },
      insertSave() {
        this.$refs.insertForm.validate((valid) => {
          if (valid && this.openDateValid) {
            let data = {}
            if(this.insertForm.name) data.name = this.insertForm.name
            if(this.insertForm.appellationId) data.appellationId = this.insertForm.appellationId
            if(this.insertForm.workUnit) data.workUnit = this.insertForm.workUnit
            if(this.insertForm.post) data.post = this.insertForm.post
            if(this.insertForm.phone) data.phone = this.insertForm.phone
            data.isPlayer = 2
            data.pId = this.pId
            if(this.isInsert){
              person_family_insert(data).then(res=>{
                if(res.code === 200) {
                  this.dataList.unshift(res.data)
                  this.defaultDataList.push(res.data)
                  this.init_data(this.defaultDataList)
                  this.page.totalResult+=1
                  this.$refs.XTable.setCurrentRow(this.dataList[0])
                  this.$message.success('保存成功')
                  this.insertSuccess = true
                  this.insertModal = false
                }else{
                  this.$message.error(res.message)
                }
              })
            }else{
              data.flowId = this.flowId
              person_family_update(data).then(res=>{
                if(res.code === 200) {
                  Object.assign(this.dataList[this.currentIndex],res.data)
                  this.defaultDataList.forEach(item=>{
                  	if(res.data.flowId == item.flowId){
                  	  Object.assign(item,res.data)
                  	}
                  })
                  this.init_data(this.defaultDataList)
                  this.$message.success('修改成功')
                  this.insertModal = false
                }else{
                  this.$message.error(res.message)
                }
              })
            }
          } else {
            return false;
          }
        })
      },
      insertEvent() {
        this.insertForm = {
          name: '',
          appellationId: '',
          workUnit: '',
          phone: '',
          post: '',
        }
        this.isInsert = true
        this.insertModal = true
      },
      sportChange() {
        this.insertForm.sportItemId = ''
        sport_item_by_sportId({sportId:this.insertForm.sportId}).then(res=>{
          if(res.code === 200) {
            this.sportItemData = res.data
          }
        })
      },
      printEvent() {
        let topHtml = '<h2>家庭成员</h2>'
        this.searchEvent()
        setTimeout(()=>{
          this.$refs.XTable.print({
              sheetName: '家庭成员',
              beforePrintMethod: ({content}) => {
                  return topHtml + content
              }
          })
        },1000)
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
          	currentPage: 1,
          	pageSize: this.dataList.length,
          	totalResult: this.dataList.length
            }
            this.search = true
        } else {
          this.dataList = this.defaultDataList
        }
      },
      person_family() {
        person_family(this.pId).then(res=>{
          if(res.code === 200 && res.data.length != 0) {
            let data = res.data
            this.init_data(data)
            this.$emit('empFamilyDataPrint',this.defaultDataList)
          }else{
            this.defaultDataList = []
          }
        }).then(()=>{
          this.findList()
        })
      },
      init_data(data) {
        if(data.length==0) return
        data.forEach(item=>{
          item.appellation = this.dict_appellation[item.appellationId]
        })
        this.searchProps = Object.keys(data[0])
        this.defaultDataList = data
      },
      init_dict(){
        return new Promise((resolve,reject)=>{
          getAppellation().then(res=>{
            this.dict_appellation = res
            resolve()
          })
        })
      },
      handlePageChange({currentPage,pageSize}) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
      	if(!this.search){
          this.page.currentPage = 1
      	  this.page.pageSize = this.defaultDataList.length
      	  this.findList()
      	}else{
      	  this.page.pageSize = this.dataList.length
      	}
        },
      findList() {
        this.loading = true
        setTimeout(() => {
          if(this.insertSuccess){
            this.page.totalResult = this.defaultDataList.length
            this.page.currentPage = Math.ceil(this.page.totalResult/this.page.pageSize)
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
            this.$refs.XTable.setCurrentRow(this.dataList[this.dataList.length-1])
            this.insertSuccess = false
          }else{
            this.page.totalResult = this.defaultDataList.length
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
          }
          this.loading = false
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>

</style>
